<template>
  <div class="container mx-auto py-8">
    <!-- 筛选条件 -->
    <div class="flex gap-4 mb-4">
      <select v-model="selectedBrand"  @change="filterProducts" class="border rounded p-2 truncate-select placeholder">
        <option value="" disabled selected hidden>Brand</option>
        <option v-for="brand in brands" :key="brand.MFGID" :value="brand.MFGID">{{ brand.MFG }}</option>
      </select>

      <select v-model="selectedParent"  @change="filterProducts" class="border rounded p-2 truncate-select placeholder">
        <option value="" disabled selected hidden>Parent</option>
        <option v-for="parent in parents" :key="parent.id" :value="parent.ParentID">{{ parent.ParentCategory }}</option>
      </select>

      <select v-model="selectedCategory"  @change="filterProducts" class="border rounded p-2 truncate-select placeholder">
        <option value="" disabled selected hidden>Category</option>
        <option v-for="category in categories" :key="category.id" :value="category.CategoryID">{{ category.Category }}</option>
      </select>

      <button @click="resetFilters" class="bg-gray-200 rounded p-2">Reset Filters</button>
    </div>

    <!-- 表格 -->
    <table class="min-w-full border-collapse" v-loading="product.isLoading">
      <thead>
        <tr class="bg-gray-100 font-semibold">
          <th class="border-b border-gray-300 p-2 text-center font-medium">Part #</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Brand</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Parent</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Category</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Description</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Quantity</th>
          <th class="border-b border-gray-300 p-2 text-center font-medium">Operation</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="product in product.products" :key="product.PID" class="text-center cursor-pointer" @click="handleProductClick(product)">
          <td class="border-b border-gray-200 p-2">{{ product.PID }}</td>
          <td class="border-b border-gray-200 p-2">{{ product.MFG }}</td>
          <td 
            class="border-b border-gray-200 p-2" 
            style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
            :title="product.ParentCategory"
          >
            {{ product.ParentCategory || '--' }}
          </td>
          <td class="border-b border-gray-200 p-2"
            style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
            :title="product.Category"
          >
            {{ product.Category || '--' }}
          </td>
          <td 
            class="border-b border-gray-200 p-2"
            style="max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
            :title="product.Product_Description"
          >
            {{ product.Product_Description || '--' }}
          </td>
          <td 
            @click.stop
            @mousedown.stop
            @mouseup.stop class="border-b border-gray-200 p-2"
          >
            <input type="number" min="1" v-model="product.quantity" class="border rounded p-1 w-20 focus:outline-none" />
          </td>
          <td class="border-b border-gray-200 p-2 ">
            <button class="bg-primary text-white rounded p-1 w-20 mx-2" @click.stop="submitRfq(product)">RFQ</button>
            <button class=" text-primary rounded border p-1 w-20 box-border mx-2" @click.stop="submitRfqList(product)" style="color: rgb(24, 144, 255);border: 1px solid rgb(24, 144, 255);">RFQ LIST</button>
          </td>
        </tr>
      </tbody>
      <!-- 获取数据失败 -->
      <template v-if="product.error">
        <tfoot>
          <tr>
            <td :colspan="7" class="text-center text-red-400 p-4">{{ product.error }}</td>
          </tr>
        </tfoot>
      </template>
    </table>
    <!-- <Pagination
      v-model:current-page="product.Page"
      :total="product.PageInfo.TotalResult"
      :page-size="50"
      @change="handlePageChange"
    /> -->
    <el-pagination
    style="margin-top: 20px;"
      v-model:current-page="product.Page"
      v-model:page-size="product.pageSize"
      :page-sizes="[20, 50, 100, 200]"
      :size="'default'"
      layout="total, sizes, prev, pager, next, jumper"
      :total="product.PageInfo.TotalResult"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useNuxtApp } from '#app'
import Pagination from './components/Pagination.vue';
const { $request } = useNuxtApp()
import { useRouter,useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import { useProductStore } from '~/store/productStore'
const product = useProductStore()
import { useRfqStore } from '@/store/rfqStore'
const rfq = useRfqStore()
import { ElMessage, ElMessageBox } from 'element-plus'

const products = ref([]) // 存储产品列表
const brands = ref([]) // 存储品牌列表
const parents = ref([]) // 存储父级列表
const categories = ref([]) // 存储类别列表

const selectedBrand = ref("")
const selectedParent = ref("")
const selectedCategory = ref("")

// 示例数据
const exampleProducts = [
  { partNumber: 'OHBF00037X516-PK', brand: 'Littelfuse', parent: 'Circuit Protection', category: 'Fuses', description: 'Description for product 1', quantity: 1 },
  { partNumber: 'OHBF00037X517-PK', brand: 'Littelfuse', parent: 'Circuit Protection', category: 'Fuses', description: 'Description for product 2', quantity: 1 },
  { partNumber: 'OHBF00037X518-PK', brand: 'Littelfuse', parent: 'Circuit Protection', category: 'Fuses', description: 'Description for product 3', quantity: 1 },
  { partNumber: 'OHBF00037X519-PK', brand: 'Littelfuse', parent: 'Circuit Protection', category: 'Fuses', description: 'Description for product 4', quantity: 1 },
]

// 请求品牌列表
const fetchBrands = async () => {
  try {
    const response = await $request.post('/api/v1/common/getmfglist')
    brands.value = response.Data
  } catch (error) {
    console.error('Error fetching brands:', error)
  }
}

// 请求父级分类列表
const fetchParents = async () => {
  try {
    const requestData = selectedBrand.value ? { MFGIDs: [selectedBrand.value] } : {};
    const response = await $request.post('/api/v1/common/getparentcategorylist', requestData);
    parents.value = response.Data;
  } catch (error) {
      console.error('Error fetching parents:', error);
  }
}

// 请求类别列表
const fetchCategories = async () => {
  try {
    const requestData = {
        ...(selectedBrand.value ? { MFGIDs: [selectedBrand.value] } : {}),
        ...(selectedParent.value ? { ParentIDs: [selectedParent.value] } : {})
    };
    const response = await $request.post('/api/v1/common/getcategorylist', requestData);
    categories.value = response.Data;
  } catch (error) {
      console.error('Error fetching categories:', error);
  }
}



// 过滤产品
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    return (
      (selectedBrand.value ? product.brand === selectedBrand.value : true) &&
      (selectedParent.value ? product.parent === selectedParent.value : true) &&
      (selectedCategory.value ? product.category === selectedCategory.value : true)
    )
  })
})

// 重置筛选
const resetFilters = () => {
  selectedBrand.value = ''
  selectedParent.value = ''
  selectedCategory.value = ''
  filterProducts()
}

// 修改筛选条件
const filterProducts = () => {
  product.setFilter({
    brand: selectedBrand.value,
    parent: selectedParent.value,
    category: selectedCategory.value
  })
  fetchParents()
  fetchCategories()
}

const handleProductClick = (product) => {
  // 跳转到产品详情页
  router.push(`/detail?PID=${product.PID}&StandPartNo=${product.StandPartNo}&StandMFG=${product.StandMFG}` )
}

const handleSizeChange = (val: number) => {
  product.setPageSize(val)
}
const handleCurrentChange = (val: number) => {
  product.setPage(val)
}

const submitRfq = (product) => {
  console.log('RFQ:', product)
  rfq.setData({
    PartNo: product.MFGPartNo,
    MFG: product.MFG,
  })
  router.push({
    path: '/rfq',
  })
}

const submitRfqList = (product) => {
  console.log('RFQ List:', product)
  rfq.setData({
    PartNo: product.MFGPartNo,
    MFG: product.MFG,
  })
  ElMessageBox.alert('add success', {
    confirmButtonText: 'OK',
  })
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchBrands()
  fetchParents()
  fetchCategories()
  
  // 从路由中获取筛选条件
  const { Brand, Parent, Category } = route.query
  console.log('Brand:', Brand, 'Parent:', Parent, 'Category:', Category);
  if (Brand && Brand!== 'undefined') selectedBrand.value = Brand
  if (Parent && Parent!== 'undefined') selectedParent.value = Parent
  if (Category && Category!== 'undefined') selectedCategory.value = Category
  filterProducts()
  product.fetchProducts()
})

</script>

<style scoped>
.truncate-select {
  min-width: 150px;
  max-width: 200px; /* 设置最大宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.placeholder {
  color: #999; /* 设置占位符文本的颜色 */
}

.placeholder option:not(:disabled) {
  color: #000; /* 设置其他选项的文本颜色 */
}
</style>